﻿//Login
$(function () {
    $("#signin").click(function () {
        SignIn();
    });

    $("#login").keypress(function (event) {
        if (event.which == '13') {
            SignIn();
        }
    });

    $("#forgotlink").click(function () {
        var input = {
            Email: $("#email").val()
        };

        $('<div id="forgotbody"></div>').appendTo("body").css("width", "500px");
        $("#forgotbody").load("/Security/Forgot", input, function () {
            showModal($("#forgotbody"));
        });
    });

    $("#signuplink").click(function () {
        var input = {
            Email: $("#email").val()
        };

        $('<div id="signupbody"></div>').appendTo("body").css("width", "500px");
        $("#signupbody").load("/Security/Signup", input, function () {
            showModal($("#signupbody"));
        });
    });
});

function SignIn() {

    $("#signin").hide();

    var input = {
        Email: $("#email").val(),
        Password: $("#password").val(),
        Remember: $("#remember").attr('checked')
    };

    Ajax({
        url: "/Security/Login",
        data: JSON.stringify(input),
        success: function (data) {
            if (data.IsValid == true) {
                location.href = "/Console";
            } else {
                ShowValidationErrors(data);
            }
        },
        complete: function () {
            $("#signin").show();
        }
    });
}

function ShowValidationErrors(data) {
    var msg = "";

    if (data.IsInvalidInput) {
        if (data.EmailValidationCode > 0) {
            if (data.EmailValidationCode == 1) {
                msg += "Please enter your email<br/>";
            } else if (data.EmailValidationCode == 2) {
                msg += "Email cannot be more than 50 characters<br/>";
            } else if (data.EmailValidationCode == 3) {
                msg += "Please enter a valid email<br/>";
            }
            $("#email").focus();
        }

        if (data.PasswordValidationCode > 0) {
            if (data.PasswordValidationCode == 1) {
                msg += "Please enter your password<br/>";
            } else if (data.PasswordValidationCode == 2) {
                msg += "Password cannot be more than 50 characters<br/>";
            }
            $("#password").focus();
        }
    } else if (data.IsLocked) {
        msg = "Locked for " + data.LockWaitMinutes + " minute(s)";
    } else if (data.IsInvalidPassword) {
        msg = "Invalid Email or Password. " + data.AttemptsLeft + " attempts left.";
        $("#password").val("").focus();
    } else if (data.IsNotActive) {
        msg = "User is inactive.";
    }

    if (msg.length == 0) {
        $("#notif").html("");
    } else {
        $("#notif").html("<div>" + msg + "</div>");
    }

}